import 'package:common/common.dart';

/// 公用应用语言Provider
/// 1，默认应用当前语言
/// 2，应用语言修改功能

/// 查询本地记录locale
final localeRecordProvider = FutureProvider((_) async {
  Locale locale;
  var languageCode = await SPUtils.get(CacheConstants.locale);
  if (languageCode is String) {
    locale = supportLocale.firstWhere((element) => element.languageCode == languageCode,
        orElse: () => PlatformDispatcher.instance.locale);
  } else {
    locale = PlatformDispatcher.instance.locale;
  }
  return locale;
});

/// locale提供者
final localeProvider = StateNotifierProvider((ref) {
  return ref.watch(localeRecordProvider).when(data: (locale) {
    return LocaleNotifier(locale);
  }, error: (error, _) {
    return LocaleNotifier(PlatformDispatcher.instance.locale);
  }, loading: () {
    return LocaleNotifier(PlatformDispatcher.instance.locale);
  });
});

/// locale通知
class LocaleNotifier extends StateNotifier<Locale> {
  LocaleNotifier(Locale locale) : super(locale);

  // 更新locale
  void update(Locale locale) {
    state = locale;
    SPUtils.save(CacheConstants.locale, locale.languageCode);
  }
}
